package cn.itsource.basic.base.service.impl;

import cn.itsource.basic.base.service.ICodeService;
import cn.itsource.basic.exception.MyRuntimeException;
import cn.itsource.basic.utli.CodeUtil;
import cn.itsource.basic.utli.HttpSenderTest;
import cn.itsource.basic.utli.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeServiceImpl implements ICodeService {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 实现短信验证码
     * @param map
     */
    @Override
    public void sendCode(Map<String, String> map) {
        String phone = map.get("phone");
        String codeType = map.get("codeType");
        String key = phone+":"+codeType;
        System.out.println(key);
        //1.判断redis中是否存在这个手机号
       String codekey = (String) redisTemplate.opsForValue().get("key");
        //1.生成一个验证码
        String code = StrUtils.getRandomString(6);
       if(codekey!=null){//说明已经给手机发送过验证码了
           //获取上一次发送验证码的时间
           Long time = Long.valueOf(codekey.split(":")[1]);
           if(System.currentTimeMillis()-time<60*1000){//上次发送小于60秒
               //写一个自己定义的运行异常
               throw new MyRuntimeException("操作过于频繁，请稍微再试");
           }else {
               //将Code赋值上一次一样的
               code=codekey.split(":")[0];
           }


       }
        //2.发送验证码到手机号
        try {
            //CodeUtil.sendCode(code,phone);
            HttpSenderTest.sendCode(phone,code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("本次验证码为"+code);

        //3.将验证码信息放入redis TimeUnit.MINUTES时间类型
        redisTemplate.opsForValue().set("key",code+":"+System.currentTimeMillis(),3, TimeUnit.MINUTES);
    }
}
